package com.hnzq.cloud.service.impl;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hnzq.cloud.entity.FreGoods;
import com.hnzq.cloud.entity.FreType;
import com.hnzq.cloud.exception.FreTypeException;
import com.hnzq.cloud.mapper.FreTypeMapper;
import com.hnzq.cloud.param.UpdateFreTypeParam;
import com.hnzq.cloud.repo.FreGoodsRepo;
import com.hnzq.cloud.service.FreTypeService;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author jams
 * @since 2022-02-06
 */
@Service
public class FreTypeServiceImpl extends ServiceImpl<FreTypeMapper, FreType> implements FreTypeService {

    @Resource
    private FreGoodsRepo freGoodsRepo;

    @Override
    public Boolean addFreType(String name) {
        if (name==null||name.trim().equals("")) throw  new FreTypeException("添加的类型名为空",644);
        FreType selectType = getOne(new QueryWrapper<FreType>().eq("type_name", name));
        if (selectType!=null) throw  new FreTypeException("添加的类型名已存在",611);
        FreType freType = new FreType();
        freType.setTypeName(name);
        return save(freType);
    }

    @Override
    public Boolean deleteFreType(Integer id) {
        FreType freType = getById(id);
        if (freType==null) throw new FreTypeException("所删除的类型不存在",544);
        List<FreGoods> freGoods = freGoodsRepo.selectGoodsByTypeName(freType.getTypeName());
        if (freGoods==null){
            return removeById(id);
        }else {
            throw new FreTypeException("所删除类型仍有商品在使用，不能删除",545);
        }

    }

    @Override
    public List<FreType> findAllFreTypes() {
        return list();
    }

    @Override
    public Boolean updateFreType(UpdateFreTypeParam updateFreType){
        if (updateFreType.getTypeName().trim().equals("")||updateFreType.getTypeName()==null){
            throw new FreTypeException("修改后的商品类型名不能为空",644);
        }
        FreType freType = getById(updateFreType.getTypeId());
        if (freType==null) throw new FreTypeException("所修改的类型不存在",544);
        if (freType.getTypeName().trim().equals(updateFreType.getTypeName().trim())){
            throw new FreTypeException("修改前后的类型名一样，无需进行修改",645);
        }
        freType.setTypeName(updateFreType.getTypeName());
        return saveOrUpdate(freType);
    }
}
